<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php


class MUserDevice extends MModel
{

    
    public function queryUserDeviceByDevceUUID($device_uuid) {
        $db = MDbManager::getInstance();
        $sql = "select * from ".DB_PREFIX."_user_devices where user_device_uuid=\"{$device_uuid}\"";
        $db_data = $db->selectDb($sql);

        if (empty($db_data)){
            return false;
        }
        return self::assembleDevice($db_data[0]);
    }

    
    public static function queryUserDeviceByDevceUUIDAndUserID($user_id, $device_uuid) {
        $db = MDbManager::getInstance();
        $sql = "select * from " . DB_PREFIX . "_user_devices where user_id = {$user_id} " . "and user_device_uuid = \"{$device_uuid}\"";
        $db_data = $db->selectDb($sql);

        return $db_data;
    }

    
    public function queryUserDeviceById($id) {
        $db = MDbManager::getInstance();
        $sql = "select * from ".DB_PREFIX."_user_devices where id=$id";
        $db_data = $db->selectDb($sql);

        if (empty($db_data)){
            return false;
        }
        return self::assembleDevice($db_data[0]);
    }

    
    public function addUserDevices($user_id, $device_uuid, $device_type, $device_info, $device_name) {
        $db_manager = MDbManager::getInstance();

        $created_at = $updated_at = date("Y-m-d H:i:s", time());

        $sql = "INSERT INTO ".DB_PREFIX."_user_devices(user_id, user_device_type, user_device_name, user_device_info, user_device_uuid, created_at, updated_at)".
               " VALUES ($user_id, $device_type, \"{$device_name}\", \"{$device_info}\", \"{$device_uuid}\", \"{$created_at}\", \"{$updated_at}\")";
        try {
            $db_manager->insertDb($sql);
        }
        catch (Exception $e) {
            return false;
        }
        return true;
    }

    
    private function assembleDevice($db_data){
        $this->id                  = $db_data["id"];
        $this->device_id           = $db_data["id"];
        $this->user_device_uuid    = $db_data["user_device_uuid"];
        $this->user_id             = $db_data["user_id"];
        $this->user_device_type    = $db_data["user_device_type"];
        $this->user_device_name    = $db_data["user_device_name"];
        $this->user_device_info    = $db_data["user_device_info"];
        $this->created_at          = $db_data["created_at"];
        $this->updated_at          = $db_data["updated_at"];

        return $this;
    }
    
    
    public static function deleteUserDeviceById($device_id) {
        $db_manager = MDbManager::getInstance();
        $sql = "delete from " . DB_PREFIX . "_user_devices where id = {$device_id}";
        $db_manager->deleteDb($sql);
        $sql = "delete from " . DB_PREFIX . "_server_token where ost_usa_id_ref = {$device_id}";
        $db_manager->deleteDb($sql);
    }
}
?>